<?php
/**
 * Created by PhpStorm
 * User: 
 * Date: 2023/2/20
 * Time:17:56
 */

namespace app\common\utils;

use GuzzleHttp\Client;
use think\Cache;

class WechatUtil
{

    protected $appId;
    protected $appSecret;

    public function __construct()
    {
        $this->appId = config("xcx.appId");
        $this->appSecret = config("xcx.appSecret");
    }

    /**
     * 获取openid
     */
    public function getOpenid($code)
    {
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$this->appId&secret=$this->appSecret&js_code=$code&grant_type=authorization_code";
        $client = new Client();
        $res = $client->request("get", $url);
        return json_decode($res->getBody(), true);
    }

    /**
     * 根据openid获取unionid
     */
    public function getUnionid($openid){
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->getAccessToken()."&openid=".$openid."&lang=zh_CN";
        $client = new Client();
        $res = $client->request("get", $url);
        return json_decode($res->getBody(), true);
    }

    /**
     * 获取access_token
     */
    public function getAccessToken($type=1)
    {
        if (Cache::get('access_token_'.$type)) {
            return Cache::get('access_token_'.$type);
        } else {
            if ($type == 1){
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            }else{
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".config("gzh.appId")."&secret=".config("gzh.appSecret");
            }

            $client = new Client();
            $res = $client->request("get", $url);
            $res = json_decode($res->getBody(),true);
            if (isset($res['errcode'])){
                return "";
            }

            Cache::set('access_token_'.$type, $res['access_token'], 7000);
            return $res['access_token'];
        }
    }

    /**
     * 获取手机号
     */
    public function getPhoneNumber($code){
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$this->getAccessToken();
        $client = new Client(
            ['headers'=>['Content-type'=>'application/json']]
        );
        $data = ['code'=>$code];
        $res = $client->request("post",$url,['body'=>json_encode($data)]);
        return json_decode($res->getBody(),true);
    }

    /**
     * 发送订阅消息
     */
    public function sendMessage($param){
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$this->getAccessToken();
        $data = [
            'touser'=>$param['openid'],
            'template_id'=>$param['template_id'],
            'page'=>$param['page'],
//            'miniprogram_state'=>"formal",//正式版：formal 体验版：trial
            'miniprogram_state'=>"trial",
            'lang'=>"zh_CN",
            'data'=>$param['data']
        ];
        $client = new Client(
            ['headers'=>['Content-type'=>'application/json']]
        );
        $res = $client->request("post",$url,['body'=>json_encode($data)]);
        return json_decode($res->getBody(),true);
    }

    public function getJsApiTicket() {
        $data = cache('hanixuan_ticket');
        if (!$data) {
            $accessToken = $this->getAccessToken(2);
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $client = new Client();
            $res = $client->request("get", $url);
            $res = json_decode($res->getBody(),true);

            $ticket = $res['ticket']??'';
            if ($ticket) {
                cache('hanixuan_ticket',$ticket,7000);
            }
        } else {
            $ticket = $data;
        }
        return $ticket;
    }

    public function createNonceStr($length = 16): string
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

}